﻿using System;
using System.Collections.Generic;
using System.Text;
using QD.Utill;
using QD.Snapshot.Core.Config;
using System.Windows.Forms;
using System.Threading;
using NSoup.Nodes;
using System.Text.RegularExpressions;
using NSoup.Select;
using System.Data;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.IO;
using System.Threading.Tasks;
using System.Collections.Concurrent;

namespace QD.Snapshot.Core.BLL
{
    public class Search_360 : SearchBase
    {
        public Search_360(TextBox textBox, int SleepTime)
        {
            this.textBox = textBox;
            this.SleepTime = SleepTime;
            this.copyform = "1";        //360搜索引擎
            Echo("360移动截图已启动");
        }

        HttpRequest Http = new HttpRequest("Mozilla/5.0 (Linux; Android 8.1; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.23 Mobile Safari/537.36", "");
        string htmls,msg;
        Model.TaskModel_360 taskModel = new Model.TaskModel_360();
        public override void Search(string keyword, Model.Product product, Model.WebSite company)
        {
            Thread.Sleep(SleepTime);

            htmls = string.Empty;
            Http.AddCookie("d57657ae7df573a97bae7120f50a80a0", "1", "m.so.com", DateTime.Now.AddYears(1));
            msg = Http.Requset(string.Format(Engine.URL_360, keyword), out htmls);

            IsCode_360 = CheckCode(htmls);   //是否出现验证码

            if (msg.Length > 0)
            {
                Echo(string.Format("搜索 {0} 返回错误", keyword));
            }
            else if (IsCode_360)
            {
                EchoLog("code", "360出现验证码");
                Thread.Sleep(1000);
            }
            else
            {
                Echo(string.Format("搜索 {0}", keyword));
            }

            taskModel.itemid = product.itemid;
            taskModel.keyword = keyword;
            taskModel.company = company;
            taskModel.html = htmls;
            //taskModel.autoEvent = autoEvent;

            NumHelper.Instance.SetNum360(1);    //统计搜索速度
            ThreadPool.SetMinThreads(2, 1);
            ThreadPool.SetMaxThreads(5, 3);
            ThreadPool.QueueUserWorkItem(new WaitCallback(CheckOrAdd), taskModel);
            //taskModel.autoEvent.WaitOne();
        }

        void CheckOrAdd(object obj)
        {
            Model.TaskModel_360 model = obj as Model.TaskModel_360;
            model.html = Regex.Replace(model.html, "<!--([\\s\\S].*?)-->", "").Trim();
            CheckOrAdd(model.html, model.keyword, model.itemid, model.company);
            //model.autoEvent.Set();
        }

        void CheckOrAdd(string html, string keyword, int itemid, Model.WebSite company)
        {
            NSoup.Nodes.Document doc = NSoup.NSoupClient.Parse(html);
            Regex r1 = new Regex(FixRegex(company.ShortName), RegexOptions.IgnoreCase);
            Regex r2 = new Regex(FixRegex(keyword), RegexOptions.IgnoreCase);
            Regex SiteName = new Regex(FixRegex(company.SiteName), RegexOptions.IgnoreCase);
            Regex Cellphone = new Regex(FixRegex(company.Cellphone), RegexOptions.IgnoreCase);
            Regex phone = new Regex(FixRegex(company.Phone), RegexOptions.IgnoreCase);
            try
            {
                CheckOrAdd(doc, r1, SiteName, Cellphone, phone, itemid, company.UserID, keyword);
            }
            catch (Exception ex)
            {
                Logs("error", string.Format("360_CheckOrAdd()异常:itemid={0},keyword={1},html.length={2}, error:{3}", itemid, keyword, html.Length, ex.ToString()));
            }
        }

        private object obj = new object();
        void CheckOrAdd(Document doc, Regex r1, Regex SiteName, Regex Cellphone, Regex phone, int itemid, int userid, string keyword, int page = 1)
        {
            Elements result = doc.GetElementsByClass("r-results");
            if (result == null || result.IsEmpty || result.Count < 1) return;
            Element parent = result[0];
            if (parent == null) return;

            NSoup.Select.Elements list = parent.GetElementsByClass("res-list");

            HideElementList(parent.GetElementsByClass("common-disp-block"));          //去掉每行的推荐
            HideElementList(parent.GetElementsByClass("top-rec"));  //去掉顶部的推荐
            HideElementList(parent.GetElementsByClass("img"));  //去掉所有图片
            HideElementList(parent.GetElementsByClass("new-rel"));//去掉相关推荐
            HideElementList(parent.GetElementsByClass("res-show-link"));//相关问题
            HideElementList(parent.GetElementsByClass("mb"));//相关推荐

            int index = 0;
            //bool isFirst = true;
            foreach (Element ele in list)
            {
                index++;
                if (r1.IsMatch(ele.Text()) || CheckShortNameList(ele.Text()) || CheckQJY(ele.Text(), SiteName, Cellphone, phone))
                {
                    string index_key = GetMd5(ele.GetElementsByTag("h3").Text); //第几行的key,更新时，用来确定更新哪一行
                    string platform = GetPlatform(ele.Html());    //上词的平台

                    //if (isFirst)
                    //{
                        RemoveAttr(result);
                    //    isFirst = false;
                    //}

                    //添加成功记录
                        lock (obj)
                        {
                            AddSnap(page, userid, itemid, index, keyword, result.Html(), platform, index_key);
                        }
                }
            }
        }

        protected override void RemoveAttr(Elements result)
        {
            if (result == null) return;
            Elements ele = result.Select("a");
            ele.Attr("href", "#");
            ele.RemoveAttr("data-md");
            ele.RemoveAttr("e_href");
            ele.RemoveAttr("data-scn");
            ele.RemoveAttr("data-sclon");
            ele.RemoveAttr("data-sclat");
            ele.RemoveAttr("data-ecn");
            ele.RemoveAttr("data-eclon");


            Elements div = result.Select("div");
            div.RemoveAttr("data-pcurl");
            div.RemoveAttr("data-jss");
            div.RemoveAttr("data-abtest-id");
            div.RemoveAttr("data-cat");
            div.RemoveAttr("data-disp-log");

            Elements iframe = result.Select("iframe");
            iframe.Remove();

            Elements form = result.Select("form");
            form.Remove();

            result.Select(".g-f-img-zoom-pic").Remove();

            Elements span = result.Select("span");
            span.RemoveAttr("res-show-link");
            span.RemoveAttr("data-delay-style");
            span.RemoveAttr("data-icon-type");
            

            Elements script = result.Select("script");
            script.Remove();

            Elements style = result.Select("style");
            style.Remove();

            result.Select(".hide").Remove();
            result.Select("img").Remove();
            result.Select(".gotohere").Remove();
            result.Select(".g-block").Remove();
            result.Select(".tg-wrap").Remove();
            result.Select(".new-rel").Remove();
        }
    }
}